package com.hanthink.web.controller.app.task;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.hanthink.common.constant.HttpStatus;
import com.hanthink.system.domain.manhour.FactWorkerUsed;
import com.hanthink.system.mapper.task.TaskExecuteMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hpsf.GUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hanthink.common.annotation.Log;
import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.core.controller.BaseController;
import com.hanthink.common.core.domain.AjaxResult;
import com.hanthink.common.core.domain.entity.SysUser;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.core.page.TableDataInfo;
import com.hanthink.common.enums.BusinessType;
import com.hanthink.common.utils.ServletUtils;
import com.hanthink.framework.web.service.TokenService;
import com.hanthink.system.domain.equipment.EquipConfirmLog;
import com.hanthink.system.domain.repair.Equip;
import com.hanthink.system.domain.repair.EquipSelfCheckVo;
import com.hanthink.system.domain.repair.EquipStandardPic;
import com.hanthink.system.domain.repair.EquipTaskItem;
import com.hanthink.system.domain.repair.Task;
import com.hanthink.system.domain.repair.TaskItem;
import com.hanthink.system.domain.repair.TaskSelect;
import com.hanthink.system.service.task.TaskExecuteService;
import com.hanthink.system.domain.EmClosemachineLog;
import com.hanthink.system.service.IEmClosemachineLogService;
/**
 * <p>
 * Title: EquipCheckExecuteController
 * </p>
 * <p>
 * Description: 设备点检执行
 * </p>
 * 
 * @author vondser
 * @date 2020年12月8日
 */
@RestController
@RequestMapping("/equip/check")
public class EquipCheckExecuteController extends BaseController {

	protected final Logger logger = LoggerFactory.getLogger(EquipCheckExecuteController.class);

	@Autowired
	private TaskExecuteService taskExecuteService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private IEmClosemachineLogService emClosemachineLogService;
	/**
	 * 检查设备是否存在点检任务
	 */
	@PostMapping("/isExist")
	public AjaxResult queryEquipTaskExist(@RequestBody Equip equip) {
		if (ObjectUtils.isEmpty(equip) || StringUtils.isBlank(equip.getEquipCode())) {
			return AjaxResult.error("设备条码不能为空！");
		}
		// 扫描条码，查询设备任务信息
		List<TaskItem> taskItemList = taskExecuteService.queryTaskItemInfo(equip);
		// 获取设备标图列表
		List<EquipStandardPic> imageFileList = taskExecuteService.queryStandardPicList(equip);

		AjaxResult ajax = AjaxResult.success();
		if (CollectionUtils.isNotEmpty(taskItemList)) {
			ajax.put("taskItemList", taskItemList);
		}
		if (CollectionUtils.isNotEmpty(imageFileList)) {
			List<String> taskFileList = imageFileList.stream().map(EquipStandardPic::getImagePath)
					.collect(Collectors.toList());
			ajax.put("taskFileList", taskFileList);
		}
		return ajax;
	}

	/**
	 * 根据设备查询维修单
	 */
	@PostMapping("/equipmentNoRepaired")
	public AjaxResult equipmentNoRepaired(@RequestBody Equip equip) {
		int num = taskExecuteService.equipmentNoRepaired(equip);
		AjaxResult ajax = AjaxResult.success();
		ajax.put("num", num);
		return ajax;
	}

	/**
	 * 根据点检项ID查询子选项信息
	 */
	@PostMapping("/queryTaskItemSelect")
	public AjaxResult queryTaskItemSelect(@RequestBody TaskSelect select) {
		List<TaskSelect> taskSelects = taskExecuteService.queryTaskItemSelect(select);
		AjaxResult ajax = AjaxResult.success();
		if (CollectionUtils.isNotEmpty(taskSelects)) {
			ajax.put("taskSelects", taskSelects);
		}
		return ajax;
	}

	/**
	 * 查询点检任务列表
	 */
	@PostMapping("/pointTaskList")
	public TableDataInfo queryEquipTaskExist(@RequestBody Task task) {

		startPage();
		// 获取任务列表
		List<Task> taskList = taskExecuteService.queryEquipTaskList(task);
		return getDataTable(taskList);
	}

	/**
	 * 创建点检任务
	 */
	@PostMapping("/create")
	public AjaxResult createEquipCheckTask(@RequestBody Equip equip) {

		if (ObjectUtils.isEmpty(equip) || StringUtils.isBlank(equip.getEquipCode())) {
			return AjaxResult.error("设备条码不能为空！");
		}

		// 查询设备点检任务JOB-ITEM
		List<EquipTaskItem> eqTaskItemList = taskExecuteService.queryTaskItemUnCreatedInfo(equip);

		// 获取当前登录用户
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		SysUser user = loginUser.getUser();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user", user);
		map.put("eqStatus", equip.getEqStatus());

		// 创建任务
		// EM_TASK 任务表、EM_TASK_ITEM任务项表、EM_TASK_FILE任务结果文件
		List<TaskItem> taskItemList = taskExecuteService.createTaskWithItem(eqTaskItemList, map);
		// 返回设备主图--EM_IMAGE设备图片表
		List<EquipStandardPic> imageFileList = taskExecuteService.queryStandardPicList(equip);
		AjaxResult ajax = AjaxResult.success();
		if (CollectionUtils.isNotEmpty(taskItemList)) {
			ajax.put("taskItemList", taskItemList);
		}
		if (CollectionUtils.isNotEmpty(imageFileList)) {
			List<String> taskFileList = imageFileList.stream().map(EquipStandardPic::getImagePath)
					.collect(Collectors.toList());

			ajax.put("taskFileList", taskFileList);
		}
		return ajax;
	}
	@PostMapping("/closetask")
	public TableDataInfo closetask(@RequestBody Map<String, Object> map) throws ParseException {
        //更新任务表任务状态字段
		Task tasklist = new Task();
		tasklist.setTaskCode(map.get("taskCode").toString());
		taskExecuteService.updateTaskStatusCloseTask(tasklist);
		//插入日志表
		EmClosemachineLog emClosemachineLog =new EmClosemachineLog();
		emClosemachineLog.setId(java.util.UUID.randomUUID().toString());
		emClosemachineLog.setUserid(map.get("userId").toString());
		emClosemachineLog.setTaskcode(map.get("taskCode").toString());
		emClosemachineLog.setOperationdatetime(new Date());
		emClosemachineLogService.insertEmClosemachineLog(emClosemachineLog);

		TableDataInfo tableDataInfo = new TableDataInfo();
		tableDataInfo.setCode(HttpStatus.SUCCESS);
		tableDataInfo.setMsg("任务删除成功");
		return tableDataInfo;
	}
	/**
	 * 更新或保存任务项
	 */
	@PostMapping("/saveOrUpdate")
	public AjaxResult saveOrUpdateTaskItem(@RequestBody TaskItem item) {

		List<TaskItem> itemList = new ArrayList<TaskItem>();
		itemList.add(item);
		if (CollectionUtils.isEmpty(itemList)) {
			return AjaxResult.error("任务项列表不能为空！");
		}

		// 查询设备点检任务JOB-ITEM
		boolean result = taskExecuteService.saveOrUpdateTaskItemInfo(itemList);

		if (!result) {
			return AjaxResult.error("任务项更新失败！");
		}
		return AjaxResult.success();
	}

	/**
	 * 记录确认确认日志
	 */
	@PostMapping("/saveEquipConfirmLog")
	@Log(title = "设备状态确认", businessType = BusinessType.INSERT)
	public AjaxResult saveEquipConfirmLog(@RequestBody EquipConfirmLog equipConfirmLog) {
		// 获取当前登录用户
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		SysUser user = loginUser.getUser();
		if (user.getSite() == null) {
			equipConfirmLog.setSiteKey(0L);
		} else {
			equipConfirmLog.setSiteKey(user.getSite());
		}
		equipConfirmLog.setNickName(user.getNickName());
		taskExecuteService.saveEquipConfirmLog(equipConfirmLog);
		return AjaxResult.success();
	}

	/**
	 * 更新或保存任务项
	 */
	@PostMapping("/saveOrUpdate1")
	public AjaxResult saveOrUpdateTaskItem1(@RequestBody TaskItem item) {

		List<TaskItem> itemList = new ArrayList<TaskItem>();
		itemList.add(item);
		if (CollectionUtils.isEmpty(itemList)) {
			return AjaxResult.error("任务项列表不能为空！");
		}

		// 查询设备点检任务JOB-ITEM
		boolean result = taskExecuteService.saveOrUpdateTaskItemInfo1(itemList);

		if (!result) {
			return AjaxResult.error("任务项更新失败！");
		}
		return AjaxResult.success();
	}

	/**
	 * 查询点检信息
	 */
	@PostMapping("/queryTaskItemInfo")
	public AjaxResult queryEqCheckTaskItemInfo(@RequestBody Task task) {
		if (ObjectUtils.isEmpty(task)) {
			return AjaxResult.error("点检任务Code不能为空！");
		}
		// 创建任务
		// EM_TASK 任务表、EM_TASK_ITEM任务项表、EM_TASK_FILE任务结果文件
		TaskItem item = taskExecuteService.queryTaskItemUndoInfo(task);
		// 返回设备主图--EM_IMAGE设备图片表
		return AjaxResult.success(item);
	}

	/**
	 * 查询设备列表
	 */
	@PostMapping("/getEquipList")
	public AjaxResult queryEquipList() {
		// 获取当前登录用户
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		AjaxResult ajax = AjaxResult.success();
		List<Equip> equipList = taskExecuteService.queryEquipList(loginUser);
		if (CollectionUtils.isNotEmpty(equipList)) {
			// 获取车间列表
			List<String> areaList = equipList.stream().map(Equip::getAreaKey).distinct().collect(Collectors.toList());	
			// 匹配用户部门
			String userDept = loginUser.getUser().getDept().getDeptName();
			for (String str : areaList) {
				if(StringUtils.isNotEmpty(userDept) && userDept.equals(str)) {
					areaList = new ArrayList<String>();
					areaList.add(str);
					break;
				}
			}
			ajax.put("areaList", areaList);
		}
		if (CollectionUtils.isNotEmpty(equipList)) {
			equipList.stream().forEach(equip -> {
				if (StringUtils.isNotBlank(equip.getStatus())) {
					equip.setEqState(equip.getStatus().equals(BusinessConstants.EQUIP_STATE_RUNING));
				}
			});
			ajax.put("equipList", equipList);
		}
		return ajax;
	}

	/**
	 * 更新设备信息
	 */
	@PostMapping("/updateEquip")
	public AjaxResult updateEquipInfo(@RequestBody Equip equip) {

		// 获取当前登录用户
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		boolean result = taskExecuteService.updateEquipInfo(equip, loginUser);
		if (!result) {
			return AjaxResult.error("更新设备状态失败！");
		}
		return AjaxResult.success();
	}

	/**
	 * 更新设备预约信息
	 */
	@PostMapping("/updateEquipAppointment")
	public AjaxResult updateEquipAppointment(@RequestBody Equip equip) {

		// 获取当前登录用户
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		// 系统需更新当前项目结果为跳过
		boolean result = taskExecuteService.updateEquipAppointment(equip, loginUser);
		if (!result) {
			return AjaxResult.error("更新设备预约时间失败！");
		}
		return AjaxResult.success();
	}

	/**
	 * 更新点检信息
	 */
	@PostMapping("/update")
	public AjaxResult updateEquipCheckInfo(TaskItem item) {
		AjaxResult ajax = AjaxResult.success();
		// 系统需更新当前项目结果为跳过
		return ajax;
	}

	/**
	 * 保存自修信息
	 */
	@PostMapping("/saveSelfCheck")
	public AjaxResult saveEquipSelfCheckInfo(@RequestBody EquipSelfCheckVo scv) {

		// 获取当前登录用户
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

		boolean result = taskExecuteService.saveEquipSelfCheckInfo(scv, loginUser);
		if (!result) {
			return AjaxResult.error("保存自修信息！");
		}
		return AjaxResult.success();
	}

	/**
	 * 更新自修信息
	 */
	@PostMapping("/updateSelfCheck")
	public AjaxResult updateEquipSelfCheckInfo(@RequestBody EquipSelfCheckVo item) {
		AjaxResult ajax = AjaxResult.success();
		return ajax;
	}
}
